package controller;

import java.io.IOException;
import java.util.ArrayList;

import DAO.CookingDAO;
import DTO.CookingDTO;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import constants.StringConstants;

/**
 * Servlet implementation class CookingServlet
 */
public class CookingServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final String COOKING_SERVLET = "CookingServlet";

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public CookingServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		if (request.getSession().getAttribute("ADMIN_USERNAME") != null) {
			CookingDAO dao = new CookingDAO();
			ArrayList<CookingDTO> list = dao.select();

			request.setAttribute("COOKINGLIST", list);
			RequestDispatcher rd = request
					.getRequestDispatcher("admin/cooking.jsp");
			rd.forward(request, response);
		} else {
			response.sendRedirect("admin/admin-login.html");
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		if (request.getSession().getAttribute("ADMIN_USERNAME") != null) {
			request.setCharacterEncoding("UTF-8");
			String action = request.getParameter("action");
			if (action.equals(StringConstants.ADD)) {
				String name = request.getParameter("name");
				CookingDTO cooking = new CookingDTO(0, name);
				CookingDAO dao = new CookingDAO();
				dao.add(cooking);

				response.sendRedirect(COOKING_SERVLET);
			} else if (action.equals(StringConstants.EDIT)) {
				int id = Integer.parseInt(request.getParameter("id"));
				String name = request.getParameter("name");
				CookingDTO cooking = new CookingDTO(id, name);
				CookingDAO dao = new CookingDAO();
				dao.update(cooking);

				response.sendRedirect(COOKING_SERVLET);
			} else if (action.equals(StringConstants.DELETE)) {
				int id = Integer.parseInt(request.getParameter("id"));
				CookingDAO dao = new CookingDAO();
				dao.delete(id);

				response.sendRedirect(COOKING_SERVLET);
			}
		} else {
			response.sendRedirect("admin/admin-login.html");
		}
	}

}
